using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EffectManager : MonoBehaviour
{
    [Header("特效预制体")]
    public GameObject explosionEffectPrefab;
    public GameObject hitEffectPrefab;
    public GameObject powerUpEffectPrefab;
    public GameObject shieldEffectPrefab;
    public GameObject screenClearEffectPrefab;
    
    [Header("粒子系统设置")]
    public int maxParticleCount = 1000;
    public float particleLifetime = 2f;
    public bool useObjectPooling = true;
    
    [Header("屏幕震动设置")]
    public float shakeIntensity = 0.5f;
    public float shakeDuration = 0.2f;
    public AnimationCurve shakeCurve = AnimationCurve.EaseInOut(0, 1, 1, 0);
    
    [Header("闪光效果设置")]
    public Color flashColor = Color.white;
    public float flashDuration = 0.1f;
    public AnimationCurve flashCurve = AnimationCurve.EaseInOut(0, 1, 1, 0);
    
    [Header("慢动作效果设置")]
    public float slowMotionScale = 0.3f;
    public float slowMotionDuration = 2f;
    public AnimationCurve slowMotionCurve = AnimationCurve.EaseInOut(0, 1, 1, 0);
    
    [Header("调试设置")]
    public bool showDebugInfo = true;
    public bool showEffectBounds = true;
    
    // 单例模式
    public static EffectManager Instance { get; private set; }
    
    // 对象池
    private Dictionary<string, Queue<GameObject>> effectPools;
    private Transform effectContainer;
    
    // 摄像机引用
    private Camera mainCamera;
    private Vector3 originalCameraPosition;
    
    // 屏幕闪光
    private SpriteRenderer flashRenderer;
    
    // 当前效果状态
    private bool isShaking = false;
    private bool isFlashing = false;
    private bool isSlowMotion = false;
    
    void Awake()
    {
        // 单例模式实现
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
            InitializeEffectManager();
        }
        else
        {
            Destroy(gameObject);
        }
    }
    
    void InitializeEffectManager()
    {
        // 获取主摄像机
        mainCamera = Camera.main;
        if (mainCamera == null)
        {
            mainCamera = FindObjectOfType<Camera>();
        }
        
        if (mainCamera != null)
        {
            originalCameraPosition = mainCamera.transform.position;
        }
        
        // 创建特效容器
        GameObject container = GameObject.Find("Effects");
        if (container == null)
        {
            container = new GameObject("Effects");
        }
        effectContainer = container.transform;
        
        // 初始化对象池
        if (useObjectPooling)
        {
            InitializeObjectPools();
        }
        
        // 创建屏幕闪光对象
        CreateScreenFlash();
        
        Debug.Log("特效管理器已初始化");
    }
    
    void InitializeObjectPools()
    {
        effectPools = new Dictionary<string, Queue<GameObject>>();
        
        // 为每种特效类型创建对象池
        CreateEffectPool("Explosion", 20);
        CreateEffectPool("Hit", 50);
        CreateEffectPool("PowerUp", 10);
        CreateEffectPool("Shield", 5);
        CreateEffectPool("ScreenClear", 2);
        
        Debug.Log("特效对象池已初始化");
    }
    
    void CreateEffectPool(string effectType, int poolSize)
    {
        Queue<GameObject> pool = new Queue<GameObject>();
        
        for (int i = 0; i < poolSize; i++)
        {
            GameObject effectObj = CreateDefaultEffect(effectType);
            effectObj.SetActive(false);
            effectObj.transform.SetParent(effectContainer);
            pool.Enqueue(effectObj);
        }
        
        effectPools[effectType] = pool;
    }
    
    GameObject CreateDefaultEffect(string effectType)
    {
        GameObject effectObj = new GameObject($"Effect_{effectType}");
        
        // 添加粒子系统
        ParticleSystem particles = effectObj.AddComponent<ParticleSystem>();
        var main = particles.main;
        main.startLifetime = particleLifetime;
        main.startSpeed = 5f;
        main.maxParticles = 100;
        
        // 根据特效类型设置不同的参数
        switch (effectType)
        {
            case "Explosion":
                ConfigureExplosionEffect(particles);
                break;
            case "Hit":
                ConfigureHitEffect(particles);
                break;
            case "PowerUp":
                ConfigurePowerUpEffect(particles);
                break;
            case "Shield":
                ConfigureShieldEffect(particles);
                break;
            case "ScreenClear":
                ConfigureScreenClearEffect(particles);
                break;
        }
        
        // 添加自动销毁组件
        EffectAutoDestroy autoDestroy = effectObj.AddComponent<EffectAutoDestroy>();
        autoDestroy.lifetime = particleLifetime + 1f;
        
        return effectObj;
    }
    
    void ConfigureExplosionEffect(ParticleSystem particles)
    {
        var main = particles.main;
        main.startColor = new Color(1f, 0.5f, 0f, 1f); // 橙色
        main.startSize = 0.5f;
        main.startSpeed = 8f;
        
        var emission = particles.emission;
        emission.rateOverTime = 0;
        emission.SetBursts(new ParticleSystem.Burst[]
        {
            new ParticleSystem.Burst(0f, 30)
        });
        
        var shape = particles.shape;
        shape.shapeType = ParticleSystemShapeType.Circle;
        shape.radius = 0.1f;
        
        var velocityOverLifetime = particles.velocityOverLifetime;
        velocityOverLifetime.enabled = true;
        velocityOverLifetime.radial = new ParticleSystem.MinMaxCurve(5f);
        
        var colorOverLifetime = particles.colorOverLifetime;
        colorOverLifetime.enabled = true;
        Gradient gradient = new Gradient();
        gradient.SetKeys(
            new GradientColorKey[] { new GradientColorKey(Color.yellow, 0f), new GradientColorKey(Color.red, 0.5f), new GradientColorKey(Color.black, 1f) },
            new GradientAlphaKey[] { new GradientAlphaKey(1f, 0f), new GradientAlphaKey(1f, 0.5f), new GradientAlphaKey(0f, 1f) }
        );
        colorOverLifetime.color = gradient;
    }
    
    void ConfigureHitEffect(ParticleSystem particles)
    {
        var main = particles.main;
        main.startColor = Color.white;
        main.startSize = 0.2f;
        main.startSpeed = 3f;
        main.startLifetime = 0.5f;
        
        var emission = particles.emission;
        emission.rateOverTime = 0;
        emission.SetBursts(new ParticleSystem.Burst[]
        {
            new ParticleSystem.Burst(0f, 10)
        });
        
        var shape = particles.shape;
        shape.shapeType = ParticleSystemShapeType.Cone;
        shape.angle = 45f;
    }
    
    void ConfigurePowerUpEffect(ParticleSystem particles)
    {
        var main = particles.main;
        main.startColor = Color.yellow;
        main.startSize = 0.3f;
        main.startSpeed = 2f;
        main.startLifetime = 1f;
        
        var emission = particles.emission;
        emission.rateOverTime = 20;
        
        var shape = particles.shape;
        shape.shapeType = ParticleSystemShapeType.Circle;
        shape.radius = 1f;
        
        var velocityOverLifetime = particles.velocityOverLifetime;
        velocityOverLifetime.enabled = true;
        velocityOverLifetime.orbitalY = new ParticleSystem.MinMaxCurve(0.5f);
    }
    
    void ConfigureShieldEffect(ParticleSystem particles)
    {
        var main = particles.main;
        main.startColor = Color.cyan;
        main.startSize = 0.1f;
        main.startSpeed = 1f;
        main.startLifetime = 2f;
        
        var emission = particles.emission;
        emission.rateOverTime = 50;
        
        var shape = particles.shape;
        shape.shapeType = ParticleSystemShapeType.Circle;
        shape.radius = 1.5f;
        
        var velocityOverLifetime = particles.velocityOverLifetime;
        velocityOverLifetime.enabled = true;
        velocityOverLifetime.orbitalY = new ParticleSystem.MinMaxCurve(1f);
    }
    
    void ConfigureScreenClearEffect(ParticleSystem particles)
    {
        var main = particles.main;
        main.startColor = Color.white;
        main.startSize = 1f;
        main.startSpeed = 10f;
        main.startLifetime = 1f;
        
        var emission = particles.emission;
        emission.rateOverTime = 0;
        emission.SetBursts(new ParticleSystem.Burst[]
        {
            new ParticleSystem.Burst(0f, 100)
        });
        
        var shape = particles.shape;
        shape.shapeType = ParticleSystemShapeType.Box;
        shape.scale = new Vector3(20f, 20f, 1f);
        
        var velocityOverLifetime = particles.velocityOverLifetime;
        velocityOverLifetime.enabled = true;
        velocityOverLifetime.radial = new ParticleSystem.MinMaxCurve(15f);
    }
    
    void CreateScreenFlash()
    {
        GameObject flashObj = new GameObject("ScreenFlash");
        flashObj.transform.SetParent(effectContainer);
        
        flashRenderer = flashObj.AddComponent<SpriteRenderer>();
        flashRenderer.color = new Color(flashColor.r, flashColor.g, flashColor.b, 0f);
        flashRenderer.sortingOrder = 1000; // 确保在最前面
        
        // 创建一个覆盖整个屏幕的精灵
        Texture2D flashTexture = new Texture2D(1, 1);
        flashTexture.SetPixel(0, 0, Color.white);
        flashTexture.Apply();
        
        Sprite flashSprite = Sprite.Create(flashTexture, new Rect(0, 0, 1, 1), new Vector2(0.5f, 0.5f));
        flashRenderer.sprite = flashSprite;
        
        // 设置大小以覆盖整个屏幕
        if (mainCamera != null)
        {
            float height = 2f * mainCamera.orthographicSize;
            float width = height * mainCamera.aspect;
            flashObj.transform.localScale = new Vector3(width, height, 1f);
            flashObj.transform.position = mainCamera.transform.position + Vector3.forward * 5f;
        }
        
        flashObj.SetActive(false);
    }
    
    // 公共方法：播放爆炸特效
    public void PlayExplosionEffect(Vector3 position, float scale = 1f)
    {
        GameObject effect = GetPooledEffect("Explosion");
        if (effect != null)
        {
            effect.transform.position = position;
            effect.transform.localScale = Vector3.one * scale;
            effect.SetActive(true);
            
            ParticleSystem particles = effect.GetComponent<ParticleSystem>();
            if (particles != null)
            {
                particles.Play();
            }
            
            if (showDebugInfo)
            {
                Debug.Log($"播放爆炸特效在位置: {position}");
            }
        }
    }
    
    // 公共方法：播放击中特效
    public void PlayHitEffect(Vector3 position, Vector3 direction)
    {
        GameObject effect = GetPooledEffect("Hit");
        if (effect != null)
        {
            effect.transform.position = position;
            effect.transform.rotation = Quaternion.LookRotation(direction);
            effect.SetActive(true);
            
            ParticleSystem particles = effect.GetComponent<ParticleSystem>();
            if (particles != null)
            {
                particles.Play();
            }
        }
    }
    
    // 公共方法：播放道具收集特效
    public void PlayPowerUpEffect(Vector3 position)
    {
        GameObject effect = GetPooledEffect("PowerUp");
        if (effect != null)
        {
            effect.transform.position = position;
            effect.SetActive(true);
            
            ParticleSystem particles = effect.GetComponent<ParticleSystem>();
            if (particles != null)
            {
                particles.Play();
            }
        }
    }
    
    // 公共方法：播放护盾特效
    public void PlayShieldEffect(Transform target, float duration = 5f)
    {
        GameObject effect = GetPooledEffect("Shield");
        if (effect != null)
        {
            effect.transform.position = target.position;
            effect.transform.SetParent(target);
            effect.SetActive(true);
            
            ParticleSystem particles = effect.GetComponent<ParticleSystem>();
            if (particles != null)
            {
                particles.Play();
            }
            
            // 设置持续时间
            EffectAutoDestroy autoDestroy = effect.GetComponent<EffectAutoDestroy>();
            if (autoDestroy != null)
            {
                autoDestroy.lifetime = duration;
            }
        }
    }
    
    // 公共方法：播放清屏特效
    public void PlayScreenClearEffect()
    {
        GameObject effect = GetPooledEffect("ScreenClear");
        if (effect != null)
        {
            if (mainCamera != null)
            {
                effect.transform.position = mainCamera.transform.position;
            }
            effect.SetActive(true);
            
            ParticleSystem particles = effect.GetComponent<ParticleSystem>();
            if (particles != null)
            {
                particles.Play();
            }
        }
        
        // 同时播放屏幕闪光
        StartScreenFlash();
    }
    
    // 公共方法：屏幕震动
    public void StartScreenShake(float intensity = -1f, float duration = -1f)
    {
        if (isShaking) return;
        
        float shakeInt = intensity > 0 ? intensity : shakeIntensity;
        float shakeDur = duration > 0 ? duration : shakeDuration;
        
        StartCoroutine(ScreenShakeCoroutine(shakeInt, shakeDur));
    }
    
    IEnumerator ScreenShakeCoroutine(float intensity, float duration)
    {
        if (mainCamera == null) yield break;
        
        isShaking = true;
        Vector3 originalPos = originalCameraPosition;
        float elapsed = 0f;
        
        while (elapsed < duration)
        {
            elapsed += Time.unscaledDeltaTime;
            float progress = elapsed / duration;
            float shakeAmount = intensity * shakeCurve.Evaluate(1f - progress);
            
            Vector3 randomOffset = Random.insideUnitCircle * shakeAmount;
            mainCamera.transform.position = originalPos + randomOffset;
            
            yield return null;
        }
        
        mainCamera.transform.position = originalPos;
        isShaking = false;
    }
    
    // 公共方法：屏幕闪光
    public void StartScreenFlash(Color? color = null, float duration = -1f)
    {
        if (isFlashing) return;
        
        Color flashCol = color ?? flashColor;
        float flashDur = duration > 0 ? duration : flashDuration;
        
        StartCoroutine(ScreenFlashCoroutine(flashCol, flashDur));
    }
    
    IEnumerator ScreenFlashCoroutine(Color color, float duration)
    {
        if (flashRenderer == null) yield break;
        
        isFlashing = true;
        flashRenderer.gameObject.SetActive(true);
        
        float elapsed = 0f;
        while (elapsed < duration)
        {
            elapsed += Time.unscaledDeltaTime;
            float progress = elapsed / duration;
            float alpha = flashCurve.Evaluate(1f - progress);
            
            flashRenderer.color = new Color(color.r, color.g, color.b, alpha);
            
            yield return null;
        }
        
        flashRenderer.color = new Color(color.r, color.g, color.b, 0f);
        flashRenderer.gameObject.SetActive(false);
        isFlashing = false;
    }
    
    // 公共方法：慢动作效果
    public void StartSlowMotion(float scale = -1f, float duration = -1f)
    {
        if (isSlowMotion) return;
        
        float slowScale = scale > 0 ? scale : slowMotionScale;
        float slowDur = duration > 0 ? duration : slowMotionDuration;
        
        StartCoroutine(SlowMotionCoroutine(slowScale, slowDur));
    }
    
    IEnumerator SlowMotionCoroutine(float scale, float duration)
    {
        isSlowMotion = true;
        float originalTimeScale = Time.timeScale;
        
        // 渐入慢动作
        float elapsed = 0f;
        float transitionTime = 0.2f;
        
        while (elapsed < transitionTime)
        {
            elapsed += Time.unscaledDeltaTime;
            float progress = elapsed / transitionTime;
            Time.timeScale = Mathf.Lerp(originalTimeScale, scale, progress);
            yield return null;
        }
        
        Time.timeScale = scale;
        
        // 保持慢动作
        yield return new WaitForSecondsRealtime(duration - transitionTime * 2);
        
        // 渐出慢动作
        elapsed = 0f;
        while (elapsed < transitionTime)
        {
            elapsed += Time.unscaledDeltaTime;
            float progress = elapsed / transitionTime;
            Time.timeScale = Mathf.Lerp(scale, originalTimeScale, progress);
            yield return null;
        }
        
        Time.timeScale = originalTimeScale;
        isSlowMotion = false;
    }
    
    GameObject GetPooledEffect(string effectType)
    {
        if (!useObjectPooling)
        {
            return CreateDefaultEffect(effectType);
        }
        
        if (effectPools.ContainsKey(effectType) && effectPools[effectType].Count > 0)
        {
            return effectPools[effectType].Dequeue();
        }
        
        // 如果池中没有可用对象，创建新的
        return CreateDefaultEffect(effectType);
    }
    
    public void ReturnToPool(GameObject effect, string effectType)
    {
        if (!useObjectPooling)
        {
            Destroy(effect);
            return;
        }
        
        effect.SetActive(false);
        effect.transform.SetParent(effectContainer);
        
        if (effectPools.ContainsKey(effectType))
        {
            effectPools[effectType].Enqueue(effect);
        }
    }
    
    // 公共方法：清理所有特效
    public void ClearAllEffects()
    {
        if (effectContainer != null)
        {
            foreach (Transform child in effectContainer)
            {
                if (child.gameObject.activeInHierarchy)
                {
                    child.gameObject.SetActive(false);
                }
            }
        }
        
        // 停止所有协程
        StopAllCoroutines();
        
        // 重置状态
        isShaking = false;
        isFlashing = false;
        isSlowMotion = false;
        
        // 重置时间缩放
        Time.timeScale = 1f;
        
        // 重置摄像机位置
        if (mainCamera != null)
        {
            mainCamera.transform.position = originalCameraPosition;
        }
        
        Debug.Log("所有特效已清理");
    }
    
    void OnDrawGizmos()
    {
        if (showEffectBounds && effectContainer != null)
        {
            // 绘制特效容器边界
            Gizmos.color = Color.magenta;
            Gizmos.DrawWireCube(effectContainer.position, Vector3.one * 2f);
            
            // 绘制活跃特效的位置
            Gizmos.color = Color.yellow;
            foreach (Transform child in effectContainer)
            {
                if (child.gameObject.activeInHierarchy)
                {
                    Gizmos.DrawWireSphere(child.position, 0.5f);
                }
            }
        }
    }
}

// 特效自动销毁组件
public class EffectAutoDestroy : MonoBehaviour
{
    public float lifetime = 2f;
    public string effectType = "";
    
    void OnEnable()
    {
        StartCoroutine(DestroyAfterTime());
    }
    
    IEnumerator DestroyAfterTime()
    {
        yield return new WaitForSeconds(lifetime);
        
        if (EffectManager.Instance != null && !string.IsNullOrEmpty(effectType))
        {
            EffectManager.Instance.ReturnToPool(gameObject, effectType);
        }
        else
        {
            gameObject.SetActive(false);
        }
    }
}